package com.ruoyi.web.controller.train;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.domain.GfOrders;
import com.ruoyi.system.domain.GfPassenger;
import com.ruoyi.system.domain.GfSeat;
import com.ruoyi.system.domain.GfTrain;
import com.ruoyi.system.service.IGfOrdersService;
import com.ruoyi.system.service.IGfPassengerService;
import com.ruoyi.system.service.IGfSeatService;
import com.ruoyi.system.service.IGfTrainService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.date.DateTime;

/**
 * 订单信息Controller
 * 
 * @author ruoyi
 * @date 2022-06-16
 */
@RestController
@RequestMapping("/system/orders")
public class GfOrdersController extends BaseController
{
    @Autowired
    private IGfOrdersService gfOrdersService;

    /**
     * 查询订单信息列表
     */
    @PreAuthorize("@ss.hasPermi('system:orders:list')")
    @GetMapping("/list")
    public TableDataInfo list(GfOrders gfOrders)
    {
        startPage();
        SysUser user = SecurityUtils.getLoginUser().getUser();
        if (!user.isAdmin()) {
            gfOrders.setUserName(user.getUserName());
        }
        List<GfOrders> list = gfOrdersService.selectGfOrdersList(gfOrders);
        return getDataTable(list);
    }

    /**
     * 导出订单信息列表
     */
    @PreAuthorize("@ss.hasPermi('system:orders:export')")
    @Log(title = "订单信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, GfOrders gfOrders)
    {
        List<GfOrders> list = gfOrdersService.selectGfOrdersList(gfOrders);
        ExcelUtil<GfOrders> util = new ExcelUtil<GfOrders>(GfOrders.class);
        util.exportExcel(response, list, "订单信息数据");
    }

    /**
     * 获取订单信息详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:orders:query')")
    @GetMapping(value = "/{orderId}")
    public AjaxResult getInfo(@PathVariable("orderId") Long orderId)
    {
        return AjaxResult.success(gfOrdersService.selectGfOrdersByOrderId(orderId));
    }

    @Autowired
    IGfTrainService trainService;

    @Autowired
    IGfSeatService seatService;
    @Autowired
    IGfPassengerService passengerService;

    /**
     * 新增订单信息
     */
    @PreAuthorize("@ss.hasPermi('system:orders:add')")
    @Log(title = "订单信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody GfOrders order)
    {
        String trainNumber = order.getTrainId();
        String seatNum = order.getSeatNum();
        String seatId = order.getSeatId();
        String passengerId = order.getPassengerId();

        Date startDate = order.getOrderStartDate();
        if (new DateTime(startDate).isBefore(new Date())) {
            return error("发车日期,不能选择今天和今天之前的日期.");
        }
        GfTrain train = trainService.selectByTrainNumber(trainNumber);
        GfPassenger passenger = passengerService.selectGfPassengerByPassengerId(passengerId);
        GfSeat seat = seatService.selectGfSeatBySeatId(Long.valueOf(seatId));
        if (train == null) {
            return error("无法查询到此动车.动车id=" + trainNumber);
        }
        if (passenger == null) {
            return error("无法查询到此乘车人.乘车人id=" + passengerId);
        }
        if (seat == null) {
            return error("无法查询到此座位.座位id=" + seatId);
        }


        // 根据火车的发车时间(时分秒)、到站时间(时分秒),  和用户选择的 发车日期(年月日),
        // 设置订单的发车时间(年月日时分秒)和到站时间(年月日时分秒).
        LocalTime trainStartTime = train.getTrainStartTime();
        LocalTime trainEndTime = train.getTrainEndTime();
        order.setOrderStartTime(new DateTime(LocalDateTime.of(new DateTime(startDate).toLocalDateTime().toLocalDate(), trainStartTime)));
        order.setOrderEndTime(new DateTime(LocalDateTime.of(new DateTime(startDate).toLocalDateTime().toLocalDate(), trainEndTime)));
        // 身份证号字段.
        order.setPassengerId(passenger.getPassengerIdCard());
        order.setPassengerName(passenger.getPassengerName());
        order.setSeatNum(seat.getCarriageName() + "号车厢" + seat.getSeatNum() + "号");
        order.setOrderStatus(GfOrders.OrderStatusEnum.NOT_PAY.code);
        SysUser user = SecurityUtils.getLoginUser().getUser();
        order.setUserName(user.getUserName());


        // 判断火车座位冲突:::
        //  根据  发车日期,火车id,座位编号,查询是否有  状态 in ("1", "未支付  "2", "已支付) 的车票,
        //  如果有的话,就说明别人或自己已经买了当天的票,就不能再卖给别人了啦啦啦
        boolean haveDuplicateEnableOrder = gfOrdersService.haveDuplicateEnableOrder(order.getOrderStartTime(), order.getTrainId(), order.getSeatNum());
        if (haveDuplicateEnableOrder) {
            return error(String.format("[%s]的[%s]动车的[%s]座位已经售出.您可选择其他座位.",
                                       new DateTime(startDate).toString("yyyy-MM-dd"),
                                       order.getTrainId(),
                                       order.getSeatNum()));
        }
        return toAjax(gfOrdersService.insertGfOrders(order));
    }

    /**
     * 修改订单信息
     */
    @PreAuthorize("@ss.hasPermi('system:orders:edit')")
    @Log(title = "订单信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody GfOrders gfOrders)
    {
        return toAjax(gfOrdersService.updateGfOrders(gfOrders));
    }

    /**
     * 删除订单信息
     */
    @PreAuthorize("@ss.hasPermi('system:orders:remove')")
    @Log(title = "订单信息", businessType = BusinessType.DELETE)
	@DeleteMapping("/{orderIds}")
    public AjaxResult remove(@PathVariable Long[] orderIds)
    {
        return toAjax(gfOrdersService.deleteGfOrdersByOrderIds(orderIds));
    }
}
